package cn.itcast.gateway.filters;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 虎哥
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request
        ServerHttpRequest request = exchange.getRequest();
        // - 获取用户请求参数中的 access-token 参数
        MultiValueMap<String, String> params = request.getQueryParams();
        String token = params.getFirst("access-token");
        // - 判断是否为"admin"
        if(StringUtils.equals("admin", token)){
            //  - 如果是，证明已经登录，放行请求
            return chain.filter(exchange);
        }
        //  - 如果不是，证明未登录，拦截请求
        ServerHttpResponse response = exchange.getResponse();
        // 设置返回状态码
        response.setStatusCode(HttpStatus.FORBIDDEN);
        // 拦截
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        // 优先级，给了最高优先级
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
